package hng.service.impl;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import hng.component.RedisComponent;
import hng.config.AliPayConfig;
import hng.constants.Constants;
import hng.dto.OrderDataDTO;
import hng.dto.OrdersDTO;
import hng.dto.OrdersProductDTO;
import hng.enums.OrderStatusEnum;
import hng.interceptor.LoginInterceptor;
import hng.mapper.OrdersMapper;
import hng.mapper.ProductMapper;
import hng.model.LoginUser;
import hng.model.OrderItemDO;
import hng.model.OrdersDO;
import hng.service.OrderItemService;
import hng.service.OrdersService;
import hng.vo.OrderItemVO;
import hng.vo.OrderProductVO;
import hng.vo.OrdersDetailVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 告白
 * @since 2024-06-27
 */
@Slf4j
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, OrdersDO> implements OrdersService {

    @Autowired(required = false)
    private RedisComponent redisComponent;

    @Resource
    private AliPayConfig aliPayConfig;

    @Autowired(required = false)
    private OrdersService ordersService;

    @Autowired(required = false)
    private OrderItemService orderItemService;

    @Autowired(required = false)
    private ProductMapper productMapper;

    @Autowired(required = false)
    private OrdersMapper ordersMapper;

    /**
     * 用户下单
     * redis保存订单信息
     * 过期时间15分钟
     */
    @Override
    public void saveOrders(OrderDataDTO orderDataDTO) {
        // 获取当前用户ID
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        List<OrdersDTO> ordersDTO = orderDataDTO.getOrderData();
        String outTradeNo = ordersDTO.get(0).getOutTradeNo();
        for (OrdersDTO order : ordersDTO) {
            order.setUserId(loginUser.getId()); // 给订单对象赋值当前用户ID
        }
        // 格式化redisKey
        String key = String.format(Constants.REDIS_KEY_ORDER, outTradeNo);
        // 保存用户订单信息到redis，过期时间15分钟
        redisComponent.saveOrders(key, orderDataDTO);
    }

    /**
     * 支付成功
     */
    @Transactional
    @Override
    public void paySuccess(Map<String, String> params) throws AlipayApiException {
        String outTradeNo = params.get("out_trade_no");
        String tradeNo = params.get("trade_no");
        Double buyerPayAmount = Double.parseDouble(params.get("buyer_pay_amount"));
        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, aliPayConfig.getAlipayPublicKey(), "UTF-8"); // 验证签名
        // 支付宝验签不通过
        if (!checkSignature) {
            return;
        }
        // 从redis拿订单信息
        String key = String.format(Constants.REDIS_KEY_ORDER, outTradeNo);
        OrderDataDTO orderDataDTO = (OrderDataDTO) redisComponent.get(key);
        if (orderDataDTO == null) {
            return;
        }
        redisComponent.delKey(key);
        List<OrdersDTO> ordersDTOS = orderDataDTO.getOrderData();
        // 获取到用户订单信息
        List<OrdersDO> ordersDOList = ordersDTOS.stream().map(obj -> {
            OrdersDO ordersDO = new OrdersDO();
            BeanUtils.copyProperties(obj, ordersDO);
            ordersDO.setPaymentMethod("alipay");
            ordersDO.setTradeNo(tradeNo);
            ordersDO.setOrderStatus(OrderStatusEnum.PENDING_SHIPMENT.getCode());
            ordersDO.setPaymentTime(LocalDateTime.now());
            return ordersDO;
        }).collect(Collectors.toList());

        // 插入订单表
        ordersService.saveBatch(ordersDOList);
        // 插入订单明细表
        Integer userid = ordersDOList.get(0).getUserId();
        for (int i = 0; i < ordersDOList.size(); i++) {
            Integer orderId = ordersDOList.get(i).getId();
            Integer storeId = ordersDOList.get(i).getStoreId();
            List<OrdersProductDTO> productList = ordersDTOS.get(i).getProductList();
            // 订单明细
            List<OrderItemDO> orderItemDOList = productList.stream().map(obj -> {
                OrderItemDO orderItemDO = new OrderItemDO();
                orderItemDO.setOrderId(orderId);
                orderItemDO.setUserId(userid);
                orderItemDO.setProductId(obj.getProductId());
                orderItemDO.setStoreId(storeId);
                orderItemDO.setProductPrice(obj.getPrice());
                orderItemDO.setProductNum(obj.getQuantity());
                orderItemDO.setProductSpec(obj.getSpecName());

                // 更新商品的销量
                productMapper.updateProductSales(obj.getProductId(), obj.getQuantity());
                return orderItemDO;
            }).collect(Collectors.toList());
            // 批量插入当前商家商品的订单明细
            orderItemService.saveBatch(orderItemDOList);
        }
    }

    /**
     * 查询订单商品详情
     */
    @Transactional
    @Override
    public List<OrderProductVO> getOrderProduct(Integer orderId) {
        List<OrderProductVO> orderProductVOList = ordersMapper.getProductsByOrderId(orderId);
        return orderProductVOList;
    }

    /**
     * 用户查询订单详情
     */
    @Override
    public List<OrdersDetailVO> orderInfo(Integer orderStatus) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        // 创建条件构造器
        LambdaQueryWrapper<OrdersDO> wrapper = new LambdaQueryWrapper<>();
        // 订单状态 等于0表示查所有 其他等于状态
        if (orderStatus != 0) {
            wrapper.eq(OrdersDO::getOrderStatus, orderStatus);
        }
        wrapper.eq(OrdersDO::getUserId, loginUser.getId())
                .orderByDesc(OrdersDO::getCreateTime);
        // 查询用户订单列表
        List<OrdersDO> ordersDOList = ordersMapper.selectList(wrapper);
        List<OrdersDetailVO> list = ordersDOList.stream().map(obj -> {
            OrdersDetailVO ordersDetailVO = new OrdersDetailVO();
            BeanUtils.copyProperties(obj, ordersDetailVO);
            // 查询订单详情
            List<OrderItemVO> orderItemVOList = ordersMapper.selectOrderItems(obj.getId());
            // 赋值
            ordersDetailVO.setOrderItems(orderItemVOList);
            return ordersDetailVO;
        }).collect(Collectors.toList());
        return list;
    }

    /**
     * 用户确认收货
     */
    @Override
    public void receiveGoods(Integer orderId) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();
        OrdersDO ordersDO = new OrdersDO();
        ordersDO.setId(orderId);
        ordersDO.setUserId(loginUser.getId());
        ordersDO.setOrderStatus(4);
        ordersMapper.updateById(ordersDO);
    }
}
